﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using InterfaceLibrary;

namespace InsertionSort
{
    /*
    *  InsertionSort algorithm
    *  source:  http://en.csharp-online.net/Insertion_Sort
    *  
    *  Implemented as it's own library with minimal changes from
    *  original definition. Comments edited and/or added by 
    *  David Boarman.
    * **/
    public class InsertionSorter : ISorter
    {
        #region Fields
        //  Fields

        int[] array;
        #endregion

        #region Constructors
        //  Constructors

        public InsertionSorter ( int[] Source )
        {
            //  create independent copy of array
            array = new int[ Source.Length ];
            Source.CopyTo ( array, 0 );
        }
        #endregion

        #region Functions
        //  Functions

        #region ISorter Members

        public void Sort ( )
        {
            SortArray ( );
        }

        #endregion

        public void SortArray ( )
        {
            int indexer;
            int position;
            int value;

            for (indexer = 1 ; indexer < array.Length ; indexer++)
            {
                value = array[ indexer ];
                position = indexer;

                while (( position > 0 ) && ( array[ position - 1 ] > value ))
                {
                    array[ position ] = array[ position - 1 ];
                    position = position - 1;
                }

                array[ position ] = value;
            }
        }
        #endregion

        #region Properties
        //  Properties

        public IEnumerable<int> SortedList
        {
            get { return array; }
        }

        #endregion
    }
}
